﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Interfaces;
using DAOBase;
using Entities;
using DAOExceptions;
using Utilites;

namespace Repository
{
    public class RoleRepository : IRepository<Role>
    {
        private Lazy<List<Role>> roles = new Lazy<List<Role>>(() => { return LoadRoles(); });

        private static IRoleDAO role_dao;

        public RoleRepository()
        {
            var facade = new DAOFacade();
            if (role_dao == null)
                role_dao = facade.GetFactory().GetRoleDAO();
        }

        private static List<Role> LoadRoles()
        {
            var roles_ctr = role_dao.GetRolesList();
            if (roles_ctr == null || roles_ctr.Count() == 0)
            {
                throw new DAOException("Couldn't load roles from database");
            }
            return roles_ctr;
        }

        public SmartDictionary GetAllObjects()
        {
            return new SmartDictionary((id) => { return null; }, roles.Value);
        }

        public void InsertObject(Role obj)
        {
            roles.Value.Add(obj);
            obj.State = EntityState.New;
        }

        public void DeleteObject(Role obj)
        {
            foreach (var obj_k in roles.Value.Where((x) => (x.ID == obj.ID)))
            {
                obj_k.State = EntityState.Deleted;
            }
        }

        public void Go()
        {
            foreach (var rec in roles.Value)
            {
                switch (rec.State)
                {
                    case EntityState.New: role_dao.AddRole(rec);
                        break;
                    case EntityState.Modified: role_dao.ModifyRole(rec); break;
                    case EntityState.Deleted: role_dao.DeleteRole(rec); break;
                }
                rec.State = EntityState.Unchanged;
            }
        }

        public void Reload()
        {
            roles = new Lazy<List<Role>>(() => { return LoadRoles(); });
            if (roles.Value == null || roles.Value.Count() == 0)
            {
                throw new DAOException("Couldn't load roles from database");
            }
        }

        public void OnTimerUpdateInvoked(object sender, EventArgs e)
        {
            Reload();
        }
    }
}
